package com.vimi8.ebb.api.product;

import com.vimi8.ebb.api.ebb.ElectricityBusinessApi;
import com.vimi8.ebb.configuration.HttpResponseEntity;
import com.vimi8.ebb.configuration.OAuth2AuthenticationImpl;
import com.vimi8.ebb.dto.ElectricityBusinessDto;
import com.vimi8.ebb.dto.ProductDTO;
import com.vimi8.ebb.dto.ProductTradingDto;
import com.vimi8.ebb.model.*;
import com.vimi8.ebb.model.Error;
import com.vimi8.ebb.service.ElectricityBusinessService;
import com.vimi8.ebb.service.EnumCategoryService;
import com.vimi8.ebb.service.GeoCodingsService;
import com.vimi8.ebb.service.PorductInfoService;
import com.vimi8.ebb.util.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import net.sf.json.JSONObject;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by renyong on 2017/2/7.
 */
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-09-19T10:01:46.405Z")
@RestController
@RequestMapping("/entity")

public class ProductController{
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger("ProductController");
    @Autowired
    private PorductInfoService porductInfoService;
    @Autowired
    private EnumCategoryService enumCategoryService;
    @Autowired
    private ElectricityBusinessService electricityBusinessService;
    @Autowired
    private GeoCodingsService geoCodingsService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value = "查询所有产品信息",notes = "查询所有产品信息",response = ProductInfo.class,tags = {"产品信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/admin/allproductinfo/",method = RequestMethod.GET)
    public HttpResponseEntity<Paginator<List<ProductInfo>>> getProductAllListAdmin(@ApiParam(value = "页码", required = true) @RequestParam(value = "start", required = true) int start,
                                                                              @ApiParam(value = "数据大小", required = true) @RequestParam(value = "size", required = true) int size,
                                                                              @ApiParam(value = "产品名称", required = false) @RequestParam(value = "productName", required = false) String productName,
                                                                              @ApiParam(value = "地址code", required = false) @RequestParam(value = "addressCode", required = false) String addressCode,
                                                                              @ApiParam(value = "开始时间", required = false) @RequestParam(value = "startTime", required = false) String startTime,
                                                                              @ApiParam(value = "结束时间", required = false) @RequestParam(value = "endTime", required = false) String endTime) {
        logger.info("Title="+"查询所有产品信息"+","+"method="+"/product/list/");
        int count = 0;
        PagesUtil pagesUtil=new PagesUtil();
        pagesUtil.setPageSize(size);
        pagesUtil.setCurrentPage(start);
        if(start<1){
            pagesUtil.setCurrentPage(1);
        }
        Paginator<List<ProductInfo>> paginator=null;

        try {
            //根据ClientId查询地址
            String quyue = electricityBusinessService.getClientAddressCode(OAuth2AuthenticationImpl.openId());
            GeoCodings geoCodings = geoCodingsService.getGeoCodingsById(quyue);
            // String geoName = geoCodings.getGeoName();
            String addressCodes= SubStringUtil.separateGeoCodeByProduct(geoCodings.getId(),geoCodings.getRegionLever()+1+"");
            StringBuilder timeSb=new StringBuilder();
            String key=start+"-"+size+"-"+productName+"-"+addressCodes;
            if(!StringUtils.isEmpty(startTime)){
                timeSb.append(startTime.replace("-",""));

            }
            if(!StringUtils.isEmpty(endTime)){
                timeSb.append(endTime.replace("-",""));
            }
            key=key+timeSb.toString();
            String paginatorCache= (String) redisTemplate.opsForValue().get(key);
            if(!StringUtils.isEmpty(paginatorCache)){
                return new HttpResponseEntity(paginatorCache,HttpStatus.OK);
            }
            List<ProductInfo> trainInfos = null;
            if(!StringUtils.isEmpty(addressCode)){
                int total = porductInfoService.productInfoTotalddAdmin(addressCode,productName,startTime,endTime);
                pagesUtil.setTotalCount(total);
                logger.info("total:////////////////////////////////"+total);
                trainInfos = porductInfoService.getProductInfoListElectAdmin(productName,addressCode,
                        (pagesUtil.getCurrentPage()-1)*size,size,startTime,endTime);
                for (int i=0;i<trainInfos.size();i++){
                    if(!StringUtils.isEmpty(trainInfos.get(i).getEnumCategoryId())){
                        EnumCategory enumCategory = enumCategoryService.getEnumCategoryById(trainInfos.get(i).getEnumCategoryId());
                        List<String> stringList =new ArrayList<>();
                        if(null!=enumCategory){
                            stringList = SubStringCategoryCodeUtil.parseParentCategory(trainInfos.get(i).getEnumCategoryId(),enumCategory.getCategoryLevel());
                        }

                        StringBuffer buffer = new StringBuffer();
                        List<String> stringList1 = null;
                        for (int j=0;j<stringList.size();j++){
                            if (j<stringList.size()-1){
                                buffer.append(enumCategoryService.getEnumCategoryById(stringList.get(j)).getCategoryName()+"/");
                            }else {
                                buffer.append(enumCategoryService.getEnumCategoryById(stringList.get(j)).getCategoryName());
                            }
                        }
                        trainInfos.get(i).setEnumCategoryName(buffer.toString());
                    }else {
                        trainInfos.get(i).setEnumCategoryName("无");
                    }
                    if(!StringUtils.isEmpty(trainInfos.get(i).getSalesAreaId())){
                        GeoCodings geoCodings1 = geoCodingsService.getGeoCodingsById(trainInfos.get(i).getSalesAreaId());
                        if (!StringUtils.isEmpty(geoCodings1))
                            trainInfos.get(i).setSalesArea(geoCodings1.getGeoName());
                    }
                }
                logger.info("total:////////////////////////////////"+trainInfos);
                paginator=new Paginator<List<ProductInfo>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                        pagesUtil.getTotalCount(),trainInfos);
            }else {
                int total = porductInfoService.productInfoTotalddAdmin(addressCodes,productName,startTime,endTime);
                pagesUtil.setTotalCount(total);
                logger.info("total:////////////////////////////////"+total);
                trainInfos = porductInfoService.getProductInfoListElectAdmin(productName,addressCodes,(pagesUtil.getCurrentPage()-1)*size,size,startTime,endTime);
                for (int i=0;i<trainInfos.size();i++){
                    if(!StringUtils.isEmpty(trainInfos.get(i).getEnumCategoryId())){
                        EnumCategory enumCategory = enumCategoryService.getEnumCategoryById(trainInfos.get(i).getEnumCategoryId());
                        List<String> stringList = SubStringCategoryCodeUtil.parseParentCategory(trainInfos.get(i).getEnumCategoryId(),enumCategory.getCategoryLevel());
                        StringBuffer buffer = new StringBuffer();
                        List<String> stringList1 = null;
                        for (int j=0;j<stringList.size();j++){
                            if (j<stringList.size()-1){
                                buffer.append(enumCategoryService.getEnumCategoryById(stringList.get(j)).getCategoryName()+"/");
                            }else {
                                buffer.append(enumCategoryService.getEnumCategoryById(stringList.get(j)).getCategoryName());
                            }
                        }
                        trainInfos.get(i).setEnumCategoryName(buffer.toString());
                    }else {
                        trainInfos.get(i).setEnumCategoryName("无");
                    }
                    if(!StringUtils.isEmpty(trainInfos.get(i).getSalesAreaId())){
                        GeoCodings geoCodings1 = geoCodingsService.getGeoCodingsById(trainInfos.get(i).getSalesAreaId());
                        if (!StringUtils.isEmpty(geoCodings1))
                            trainInfos.get(i).setSalesArea(geoCodings1.getGeoName());
                    }
                }
                logger.info("total:////////////////////////////////"+trainInfos);
                paginator=new Paginator<List<ProductInfo>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                        pagesUtil.getTotalCount(),trainInfos);

                redisTemplate.opsForValue().set(key, JSONObject.fromObject(paginator).toString());

            }
            return new HttpResponseEntity<Paginator<List<ProductInfo>>>(paginator,HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("query trainInfo error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @ApiOperation(value = "查询店铺产品信息",notes = "查询店铺产品信息",response = ProductInfo.class,tags = {"产品信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/entityproductinfo/",method = RequestMethod.GET)
    public HttpResponseEntity<Paginator<List<ProductInfo>>> getProductEntityList(@ApiParam(value = "页码", required = true) @RequestParam(value = "start", required = true) int start,
                                                                                 @ApiParam(value = "数据大小", required = true) @RequestParam(value = "size", required = true) int size,
                                                                                 @ApiParam(value = "产品名称", required = false) @RequestParam(value = "productName", required = false) String productName,
                                                                                 @ApiParam(value = "店铺id", required = false) @RequestParam(value = "entityId", required = false) String entityId) {
        logger.info("Title="+"查询所有产品信息"+","+"method="+"/product/list/");
        int count = 0;
        PagesUtil pagesUtil=new PagesUtil();
        pagesUtil.setPageSize(size);
        pagesUtil.setCurrentPage(start);
        if(start<1){
            pagesUtil.setCurrentPage(1);
        }
        Paginator<List<ProductInfo>> paginator=null;

        try {
            int total = 0;
            String entity = OAuth2AuthenticationImpl.clientId();
            String job = OAuth2AuthenticationImpl.ClientOrgClass();
            if(StringUtils.isEmpty(entityId)){
                total = porductInfoService.productInfoTotalEntity(entity,productName);
            }else {
                total = porductInfoService.productInfoTotalEntity(entityId,productName);
            }

            pagesUtil.setTotalCount(total);
            logger.info("total:////////////////////////////////"+total);
            if ("org_ebb_entity".equals(job)){
                List<ProductInfo> trainInfos = null;
                if (StringUtils.isEmpty(entityId)){
                    trainInfos = porductInfoService.getProductInfoEntityList(entity,productName,(pagesUtil.getCurrentPage()-1)*size,size);
                }else {
                    trainInfos = porductInfoService.getProductInfoEntityList(entityId,productName,(pagesUtil.getCurrentPage()-1)*size,size);
                }

                for (int i=0;i<trainInfos.size();i++){
                    if(!StringUtils.isEmpty(trainInfos.get(i).getEnumCategoryId())){
                        EnumCategory enumCategory = enumCategoryService.getEnumCategoryById(trainInfos.get(i).getEnumCategoryId());
                        List<String> stringList = SubStringCategoryCodeUtil.parseParentCategory(trainInfos.get(i).getEnumCategoryId(),enumCategory.getCategoryLevel());
                        StringBuffer buffer = new StringBuffer();
                        List<String> stringList1 = null;
                        for (int j=0;j<stringList.size();j++){
                            if (j<stringList.size()-1){
                                buffer.append(enumCategoryService.getEnumCategoryById(stringList.get(j)).getCategoryName()+"/");
                            }else {
                                buffer.append(enumCategoryService.getEnumCategoryById(stringList.get(j)).getCategoryName());
                            }
                        }
                        trainInfos.get(i).setEnumCategoryName(buffer.toString());
                    }else {
                        trainInfos.get(i).setEnumCategoryName("无");
                    }
                    if(!StringUtils.isEmpty(trainInfos.get(i).getSalesAreaId())){
                        GeoCodings geoCodings1 = geoCodingsService.getGeoCodingsById(trainInfos.get(i).getSalesAreaId());
                        if (!StringUtils.isEmpty(geoCodings1))
                            trainInfos.get(i).setSalesArea(geoCodings1.getGeoName());
                    }
                }
                logger.info("total:////////////////////////////////"+trainInfos);
                paginator=new Paginator<List<ProductInfo>>(pagesUtil.getCurrentPage(),pagesUtil.getPageSize(),pagesUtil.getTotalPage(),
                        pagesUtil.getTotalCount(),trainInfos);
                return new HttpResponseEntity<Paginator<List<ProductInfo>>>(paginator,HttpStatus.OK);
            }else {
                logger.info("total:////////////////////////////////"+"hahhahahahahahahaha");
                return new HttpResponseEntity(new Error().error("无数据").errorDescription(""),HttpStatus.INTERNAL_SERVER_ERROR);
            }

        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("query productInfo error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @ApiOperation(value = "按产品ID查询产品信息",notes = "按产品ID查询产品信息",response = ProductInfo.class,tags = {"产品信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/productinfo/",method = RequestMethod.GET)
    public HttpResponseEntity<ProductInfo> getProductInfo(@ApiParam(value = "产品ID", required = true) @RequestParam(value = "id", required = true) String id) {
        logger.info("Title="+"按产品ID查询产品信息"+","+"method="+"/product/list/");

        ProductInfo paginator=null;
        try {
            paginator = porductInfoService.getProductInfo(id);
            if (!StringUtils.isEmpty(paginator.getEnumCategoryId())){
                EnumCategory enumCategory = enumCategoryService.getEnumCategoryById(paginator.getEnumCategoryId());
                List<String> stringList = SubStringCategoryCodeUtil.parseParentCategory(paginator.getEnumCategoryId(),enumCategory.getCategoryLevel());
                StringBuffer buffer = new StringBuffer();
                List<String> stringList1 = null;
                for (int i=0;i<stringList.size();i++){
                    if (i<stringList.size()-1){
                        buffer.append(enumCategoryService.getEnumCategoryById(stringList.get(i)).getCategoryName()+"/");
                    }else {
                        buffer.append(enumCategoryService.getEnumCategoryById(stringList.get(i)).getCategoryName());
                    }
                }
                paginator.setEnumCategoryName(buffer.toString());
            }else {
                paginator.setEnumCategoryName("无");
            }

            return new HttpResponseEntity<ProductInfo>(paginator,HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("query productInfo error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @ApiOperation(value = "添加产品信息",notes = "添加产品信息",response = String.class,tags = {"产品信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/product/",method = RequestMethod.POST)
    public HttpResponseEntity<String> addProductInfo(@ApiParam(value = "产品信息",required = true) @RequestBody(required = true) ProductInfo productInfo){
        int count=0;
        try {
            productInfo.setId(UUID.randomUUID().toString());
            productInfo.setElectricityBusinessId(OAuth2AuthenticationImpl.clientId());
            count=  porductInfoService.insertProductInfo(productInfo);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("insert trainInfo error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
    }

    @ApiOperation(value = "删除产品信息",notes = "删除产品信息",response = String.class,tags = {"产品信息"})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 500, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/product/",method = RequestMethod.DELETE)
    public HttpResponseEntity<String> deleteTrainInfoById(@ApiParam(value = "产品ID", required = true) @RequestParam(value = "id", required = true) String id){
        logger.info("id="+id);
        int count=0;
        try {
            count=porductInfoService.deleteTraInfoById(id);
            return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
        } catch (Exception e) {
            return new HttpResponseEntity(new Error().error("query productInfo error").errorDescription(e.getMessage()),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @ApiOperation(value = "批量删除产品信息", notes = "删除产品信息.参数形如：'xxxx','xxxx','xxxx'", response = String.class, tags={ "产品信息", })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 200, message = "失败,返回消息", response = String.class) })
    @RequestMapping(value = "/delSelectedAllProduct/",
            method = RequestMethod.DELETE)
    HttpResponseEntity<String> deleteSelectedAllProductInfo(@ApiParam(value = "ids", required = true) @RequestBody(required = true) String ids){
        int count= 0;
        try{
            count=porductInfoService.deleteProductInfoByIds(ids);
            return new HttpResponseEntity<String>(count+"",HttpStatus.OK);
        }catch (Exception e){
            return new HttpResponseEntity(new Error().error("sql error").errorDescription(e.getMessage()),HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @ApiOperation(value = "修改产品信息", notes = "修改产品信息.", response = String.class,
            tags = {"产品信息",})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回影响行数", response = String.class),
            @ApiResponse(code = 200, message = "失败,返回消息", response = String.class)})
    @RequestMapping(value = "/product/",
            method = RequestMethod.PUT)
    public HttpResponseEntity<String> updateProductInfo(@ApiParam(value = "产品信息", required = true) @RequestBody ProductInfo productInfo) {
        int count = 0;
        try {
            count = porductInfoService.updateProductInfo(productInfo);
        } catch (Exception e) {
            Error error = new Error().error("update error").errorDescription("update error");
            new HttpResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<String>(count + "", HttpStatus.OK);
    }



    @ApiOperation(value = "导入产品信息", notes = "导入产品信息.", response = String.class,
            tags = {"产品信息",})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回导入成功的提示信息", response = String.class),
            @ApiResponse(code = 200, message = "失败,返回消息", response = String.class)})
    @RequestMapping(value = "/product/import",
            method = RequestMethod.POST)
    public HttpResponseEntity<Object> importProduct(@RequestParam("file") MultipartFile file) {
        logger.info("requestUrl=" + "/product/import");
        Error error = new Error();
        int count=0;
        if (file == null) {
            error.error("upload file can't be empty").errorDescription("import error");
            return new HttpResponseEntity<Object>(error, HttpStatus.MULTI_STATUS);
        }
        List<ProductInfo> productInfos = readproductInfo(file);
        try {
            count=  porductInfoService.batchProductInfoBusiness(productInfos);
//            for (ProductInfo productInfo : productInfos) {
//                porductInfoService.insertProductInfo(productInfo);
//            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            error.error("internal server error").errorDescription("import error "+e.getMessage());
            return new HttpResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<Object>(count,HttpStatus.OK);
    }

    @ApiOperation(value = "导入产品信息", notes = "导入产品信息.", response = String.class,
            tags = {"产品信息",})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回导入成功的提示信息", response = String.class),
            @ApiResponse(code = 200, message = "失败,返回消息", response = String.class)})
    @RequestMapping(value = "/product/all/import",
            method = RequestMethod.POST)
    public HttpResponseEntity<Object> importAllProduct(@RequestParam("file") MultipartFile file) {
        logger.info("requestUrl=" + "/product/all/import");
        Error error = new Error();
        int count=0;
        if (file == null) {
            error.error("upload file can't be empty").errorDescription("import error");
            return new HttpResponseEntity<Object>(error, HttpStatus.MULTI_STATUS);
        }
        List<ProductInfo> productInfos = readAllProductInfo(file);
        logger.info("productInfos="+productInfos);
        try {
            count=  porductInfoService.batchProductInfoBusiness(productInfos);
//            for (ProductInfo productInfo : productInfos) {
//                porductInfoService.insertProductInfo(productInfo);
//            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            error.error("internal server error").errorDescription("import error "+e.getMessage());
            return new HttpResponseEntity<Object>(error, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new HttpResponseEntity<Object>(count,HttpStatus.OK);
    }

    @ApiOperation(value = "导出产品信息", notes = "导出产品信息.", response = String.class,
            tags = {"产品信息",})
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功,返回导出成功的提示信息", response = String.class),
            @ApiResponse(code = 200, message = "失败,返回消息", response = String.class)})
    @RequestMapping(value = "/product/export",
            method = RequestMethod.GET)
    public void exportLogistics(@ApiParam(value = "产品名称", required = false) @RequestParam(value = "productName", required = false) String productName,
                                @ApiParam(value = "地址code", required = false) @RequestParam(value = "addressCode", required = false) String addressCode,
                                @ApiParam(value = "开始时间", required = false) @RequestParam(value = "startTime", required = false) String startTime,
                                @ApiParam(value = "结束时间", required = false) @RequestParam(value = "endTime", required = false) String endTime,
                                HttpServletResponse response){
        List<ProductInfo> productInfoList = porductInfoService.getProductInfoListName(productName,addressCode,startTime,endTime);
        logger.info("productInfoList="+productInfoList);
        List<ProductDTO> productDTOs = new ArrayList<>();
        for(ProductInfo productInfo:productInfoList){
            ProductDTO productDTO = new ProductDTO();
            productDTO.fill(productInfo);
            productDTOs.add(productDTO);
        }
        logger.info("productDTOs="+productDTOs);
        Error error = new Error();

        String[] headers = {
                "交易量",
                "交易额",
                "销售区域",
                "产品名称",
                "产品分类",
                "销售单价",
                "店铺名字",
                "库存量",
                "库存单位",
                "交易时间"
        };
        String[] methods = {
                "getBusinessVolume",
                "getTradingVolume",
                "getSalesArea",
                "getProductName",
                "getEnumCategoryId",
                "getUnitPrice",
                "getElectricityBusinessName",
                "getStockVolume",
                "getStockUnit",
                "getTradingTime"
        };
        try {
            String filename = "产品信息";
            String filepath = "./" + filename;

            JxlExcelUtil.writeExcelObject(filepath, headers, methods, productDTOs, response);
            logger.info("filename="+filename);
            InputStream is = new FileInputStream(filepath);
            response.reset();
            response.setContentType("application/msexcel;charset=UTF-8");
            response.addHeader("Content-Disposition",
                    "attachment;   filename=\"" + new String((filename).getBytes("gbk"), "iso8859-1") + ".xls\"");
            byte[] b = new byte[100];
            int len;
            while ((len = is.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            is.close();
        } catch (Exception e) {
        }
    }


    /**
     * 读取产品信息
     * @param multipartFile
     * @return
     */
    private List readproductInfo(MultipartFile multipartFile) {
        List<ProductInfo> list = new ArrayList<ProductInfo>();
        try {
            //打开文件
            Workbook book = Workbook.getWorkbook(multipartFile.getInputStream());
            //取得第一个sheet
            Sheet sheet = book.getSheet(0);

            //取得行数
            int rows = sheet.getRows();
            logger.info("rows==" + rows);

            for (int i = 2; i < rows; i++) {
                ProductInfo productInfo = new ProductInfo();
                //产品信息ID
                productInfo.setId(UUID.randomUUID().toString());

                //交易量
                String businessVolume = sheet.getCell(0, i).getContents();
                String branchBusinessVolume = null;
                if (!StringUtils.isEmpty(businessVolume)){
                    branchBusinessVolume = businessVolume;
                }

                if (!StringUtils.isEmpty(branchBusinessVolume)) {
                    productInfo.setBusinessVolume(branchBusinessVolume);
                }
                //交易额
                String tradingVolume= sheet.getCell(1, i).getContents();
//                Float branchTradingVolume = null;
//                if (!StringUtils.isEmpty(tradingVolume)) {
//                    branchTradingVolume= Float.valueOf(tradingVolume);
//                }

                if (!StringUtils.isEmpty(tradingVolume)&&!"null".equals(tradingVolume)) {
                    productInfo.setTradingVolume(tradingVolume);
                }
                //销售区域
                String branchSalesArea = sheet.getCell(2, i).getContents();
                if (!StringUtils.isEmpty(branchSalesArea)&&!"null".equals(branchSalesArea)) {
                    productInfo.setSalesArea(branchSalesArea);
                }
                //产品名字
                String branchProductName = sheet.getCell(3, i).getContents();
                if (!StringUtils.isEmpty(branchProductName)&&!"null".equals(branchProductName)) {
                    productInfo.setProductName(branchProductName);
                }
                //产品分类ID
                String branchEnumCategoryId = sheet.getCell(4, i).getContents();
                if (!StringUtils.isEmpty(branchEnumCategoryId)&&!"null".equals(branchEnumCategoryId)) {
                    productInfo.setEnumCategoryId(branchEnumCategoryId);
                }
                //销售单价
                String branchUnitPrice = sheet.getCell(5, i).getContents();
                if (!StringUtils.isEmpty(branchUnitPrice)&&!"null".equals(branchUnitPrice)) {
                    productInfo.setUnitPrice(branchUnitPrice);
                }
                //电商ID
                String branchElectricityBusinessId = OAuth2AuthenticationImpl.clientId();
                if (!StringUtils.isEmpty(branchElectricityBusinessId)&&!"null".equals(branchElectricityBusinessId)) {
                    productInfo.setElectricityBusinessId(branchElectricityBusinessId);
                }
                //库存量
                String stockVolume= sheet.getCell(6, i).getContents();
                Float branchStockVolume = null;
                if (!StringUtils.isEmpty(stockVolume)&&!"null".equals(stockVolume)){
                    branchStockVolume = Float.valueOf(stockVolume);
                }

                if (!StringUtils.isEmpty(branchStockVolume)&&!"null".equals(branchStockVolume)) {
                    productInfo.setStockVolume(branchStockVolume);
                }
                //库存单位
                String branchStockUnit = sheet.getCell(7, i).getContents();
                if (!StringUtils.isEmpty(branchStockUnit)&&!"null".equals(branchStockUnit)) {
                    productInfo.setStockUnit(branchStockUnit);
                }
                //库存单位
                String branchTradingTime = sheet.getCell(8, i).getContents();
                if (!StringUtils.isEmpty(branchTradingTime)&&!"null".equals(branchTradingTime)) {
                    productInfo.setTradingTime(branchTradingTime);
                }
                if (!StringUtils.isEmpty(productInfo.getProductName())) {
                    list.add(productInfo);
                }
            }
            //关闭文件
            book.close();
        } catch (BiffException e) {
            logger.error("数据读取出错！", e);
        } catch (IOException e) {
            logger.error("数据读取出错！", e);
        }
        return list;
    }

    /**
     * 读取产品信息
     * @param multipartFile
     * @return
     */
    private List readAllProductInfo(MultipartFile multipartFile) {
        List<ProductInfo> list = new ArrayList<ProductInfo>();
        try {
            //打开文件
            Workbook book = Workbook.getWorkbook(multipartFile.getInputStream());
            //取得第一个sheet
            Sheet sheet = book.getSheet(0);

            //取得行数
            int rows = sheet.getRows();
            logger.info("rows==" + rows);

            for (int i = 2; i < rows; i++) {
                ProductInfo productInfo = new ProductInfo();
                //产品信息ID
                productInfo.setId(UUID.randomUUID().toString());

                //交易量
                String businessVolume = sheet.getCell(0, i).getContents();
                String branchBusinessVolume = null;
                if (!StringUtils.isEmpty(businessVolume)){
                    branchBusinessVolume = businessVolume;
                }

                if (!StringUtils.isEmpty(branchBusinessVolume)) {
                    productInfo.setBusinessVolume(branchBusinessVolume);
                }
                //交易额
                String tradingVolume= sheet.getCell(1, i).getContents();
//                Float branchTradingVolume = null;
//                if (!StringUtils.isEmpty(tradingVolume)) {
//                    branchTradingVolume= Float.valueOf(tradingVolume);
//                }

                if (!StringUtils.isEmpty(tradingVolume)&&!"null".equals(tradingVolume)) {
                    productInfo.setTradingVolume(tradingVolume);
                }
                //销售区域
                String branchSalesArea = sheet.getCell(2, i).getContents();
                if (!StringUtils.isEmpty(branchSalesArea)&&!"null".equals(branchSalesArea)) {
                    productInfo.setSalesArea(branchSalesArea);
                }
                //产品名字
                String branchProductName = sheet.getCell(3, i).getContents();
                if (!StringUtils.isEmpty(branchProductName)&&!"null".equals(branchProductName)) {
                    productInfo.setProductName(branchProductName);
                }
                //产品分类ID
                String branchEnumCategoryId = sheet.getCell(4, i).getContents();
                if (!StringUtils.isEmpty(branchEnumCategoryId)&&!"null".equals(branchEnumCategoryId)) {
                    productInfo.setEnumCategoryId(branchEnumCategoryId);
                }
                //销售单价
                String branchUnitPrice = sheet.getCell(5, i).getContents();
                if (!StringUtils.isEmpty(branchUnitPrice)&&!"null".equals(branchUnitPrice)) {
                    productInfo.setUnitPrice(branchUnitPrice);
                }
//                //电商ID
//                String branchElectricityBusinessId = OAuth2AuthenticationImpl.clientId();
//                if (!StringUtils.isEmpty(branchElectricityBusinessId)&&!"null".equals(branchElectricityBusinessId)) {
//                    productInfo.setElectricityBusinessId(branchElectricityBusinessId);
//                }
                //库存量
                String stockVolume= sheet.getCell(6, i).getContents();
                Float branchStockVolume = null;
                if (!StringUtils.isEmpty(stockVolume)&&!"null".equals(stockVolume)){
                    branchStockVolume = Float.valueOf(stockVolume);
                }

                if (!StringUtils.isEmpty(branchStockVolume)&&!"null".equals(branchStockVolume)) {
                    productInfo.setStockVolume(branchStockVolume);
                }
                //库存单位
                String branchStockUnit = sheet.getCell(7, i).getContents();
                if (!StringUtils.isEmpty(branchStockUnit)&&!"null".equals(branchStockUnit)) {
                    productInfo.setStockUnit(branchStockUnit);
                }
                //库存单位
                String branchTradingTime = sheet.getCell(8, i).getContents();
                if (!StringUtils.isEmpty(branchTradingTime)&&!"null".equals(branchTradingTime)) {
                    productInfo.setTradingTime(branchTradingTime);
                }
                //电商ID
                String branchElectricityBusinessId = sheet.getCell(9, i).getContents();
                if (!StringUtils.isEmpty(branchElectricityBusinessId)) {
                    productInfo.setElectricityBusinessId(branchElectricityBusinessId);
                }
                if (!StringUtils.isEmpty(productInfo.getProductName())) {
                    list.add(productInfo);
                }
            }
            //关闭文件
            book.close();
        } catch (BiffException e) {
            logger.error("数据读取出错！", e);
        } catch (IOException e) {
            logger.error("数据读取出错！", e);
        }
        return list;
    }
}
